package com.eningqu.aipen.ui.home;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ScreenUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.eningqu.aipen.demo.R;
import com.eningqu.aipen.sdk.bean.device.NQBtDevice;
import com.eningqu.aipen.sdk.bean.device.NQDeviceBase;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;


/**
 * Package:com.eningqu.aipen.ui.main
 * Author:starr
 * Time:2023/9/14  20:24
 * Description: 带刷新功能的列表弹窗
 */
public class ListFragmentDialog extends DialogFragment {

    private static final String TAG="ListFragmentDialog";
    ListDialogAdapter mAdapter;
    RecyclerView mRecycleView;
    SmartRefreshLayout mSmartRefreshLayout;
    public static final String KEY_CONTENT_LIST = "content_list";

    private SelectListener mSelectListener;
    ArrayList<NQDeviceBase> mDeviceLists;

    private TextView tvTitle;
    private TextView tvFresh;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        //设置content前设定
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //初始化列表
        View root = LayoutInflater.from(getContext()).inflate(R.layout.dialog_list_fragment, null);
        mRecycleView = root.findViewById(R.id.rvRecycleView);
        mRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
        mDeviceLists = getArguments() != null ? getArguments().getParcelableArrayList(KEY_CONTENT_LIST) : null;
        mAdapter = new ListDialogAdapter(mDeviceLists);//数据
        mRecycleView.setAdapter(mAdapter);
        tvFresh=root.findViewById(R.id.rerresh);
        tvTitle=root.findViewById(R.id.tvTitle);
        tvTitle.setText(getArguments().getString("tv_title","选择需要连接的设备"));
        tvFresh.setText(getArguments().getString("tv_fresh","下拉刷新蓝牙设备"));

        //adapter中item的点击事件
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            dismiss();
            //选中设备
            if (mSelectListener!=null){
                if(mAdapter!=null&&mAdapter.getItem(position)!=null){
                    Log.i(TAG, "onCreateDialog: 选中设备");
                    mSelectListener.Select(mAdapter.getItem(position));
                }
            }

        });
        mSmartRefreshLayout = root.findViewById(R.id.smartRefresh);
        //刷新设备
        mSmartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            mSmartRefreshLayout.finishRefresh(5000);
            if(mSelectListener!=null){
                Log.i(TAG, "onCreateDialog: 刷新列表");
                mSelectListener.freshDevice();
            }
        });

        dialog.setContentView(root);
        //外部点击取消
        dialog.setCanceledOnTouchOutside(true);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams layoutParams;
        if (window != null) {
            window.setBackgroundDrawableResource(R.drawable.shape_white_radiu6);
            layoutParams = window.getAttributes();
            //居中
            layoutParams.gravity = Gravity.CENTER;
            //高度宽度持平
            layoutParams.width = (int) (ScreenUtils.getScreenWidth() * 0.8);
            window.setAttributes(layoutParams);
        }
        return dialog;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void addDeviceData(NQDeviceBase data){
        if (mAdapter != null) {
            mAdapter.getData();
            if (!mAdapter.getData().contains(data)) {
                mAdapter.addData(data);
                mAdapter.notifyDataSetChanged();
            }
        }

    }
    public void setOnSelectListener(SelectListener selectListener) {
        mSelectListener = selectListener;
    }

    /**
     * 不能手动调用dismiss了，否则会调用两次code 方法
     */
    public interface SelectListener {
        void Select(NQDeviceBase deviceBase);
        void freshDevice();
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);

    }




    public static class ListDialogAdapter extends BaseQuickAdapter<NQDeviceBase, BaseViewHolder> {

        public ListDialogAdapter(@Nullable List<NQDeviceBase> data) {
            super(R.layout.dialog_list_fragment_item, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, NQDeviceBase item) {
            NQBtDevice device = (NQBtDevice) item;
            helper.setText(R.id.tvContentTitle, device.name + " " + device.mac);
        }
    }


    /**
     * 解决多次点击dialog奔溃
     */
    @Override
    public void show(@NonNull FragmentManager manager, @Nullable String tag) {
        if(manager.isDestroyed()){
            return;
        }
        try {
            manager.beginTransaction().remove(this).commit();
            super.show(manager,tag);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
